package com.scwatch.core.web.back;

import com.alibaba.fastjson.JSONObject;
import com.scwatch.common.orm.LimitRequest;
import com.scwatch.common.orm.Limitable;
import com.scwatch.common.web.Servlets;
import com.scwatch.core.constant.Constants;
import com.scwatch.core.domain.*;
import com.scwatch.core.html.HtmlGenerator;
import com.scwatch.core.html.HtmlService;
import com.scwatch.core.service.*;
import com.scwatch.core.support.Backends;
import com.scwatch.core.support.CmsException;
import com.scwatch.core.support.Context;
import com.scwatch.ext.domain.LiveBroadcast;
import com.scwatch.ext.quartz.FlashNewJob;
import com.scwatch.ext.quartz.QuartzUtils;
import com.scwatch.ext.service.LiveBroadcastService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.scwatch.core.constant.Constants.*;

/**
 * 直播 精选直播 栏目
 *
 * @author gujianlin
 */
@Controller
@RequestMapping("/core/livenode")
public class LiveNodeController {
    private static final Logger logger = LoggerFactory.getLogger(LiveNodeController.class);

    public static final int INCLUDE_CHILDREN = 0;
    public static final int INCLUDE_MULTI = 1;
    public static final int MAIN_NODE = 2;

    @Autowired
    private JpushService jpushService;

    /**
     * 推送直播
     * @param request
     * @param queryNodeId 栏目
     * @param title 推送标题
     * @return 推送结果
     */
    @RequestMapping("jpushLiveBroad.do")
    @RequiresPermissions("ext:livenode:jpushLiveBroad")
    @ResponseBody
    public String JpushLiveBroad(HttpServletRequest request,
                                 Integer queryNodeId, String title) {
        User user = Context.getCurrentUser();
        Site site = Context.getCurrentSite();
        JSONObject json = new JSONObject();
        try {
        /*---------------------------------[ 推送格式 ]--------------------------------------------*/
            Info bean = infoQuery.get(queryNodeId);

            JSONObject extr = new JSONObject();
            extr.put("newsId", bean.getRefLive().getId());//0正常、1推送直播间动态、2聊天室
            extr.put("newsTitle", bean.getRefLive().getTitle());
            extr.put("newsUrl", bean.getUrl());
            extr.put("newsType", 5);//直播间

             /*-----[封装 评论数据]------*/
            String newTitle = StringUtils.isEmpty(title) ? bean.getRefLive().getTitle() : title;
            json.put("title", newTitle);//通知内容标题
            json.put("msgTile", newTitle);//消息内容标题
            json.put("content", "直播间");//消息内容
            json.put("isOpen", false);//是否静默
            json.put("groupTag", null);//分组直播间
            json.put("extrasparam", extr);//扩展字段
            boolean isfo = jpushService.JpushIosOrAndroid(site, user, json);
            json.clear();
            String msg = "error";
            if (isfo) {
                msg = "success";
            }
            json.put("msg", msg);
        } catch (Exception e) {
            json.put("msg", "error");
        }
        return json.toJSONString();
    }


    /**
     * 直播栏目查询
     * @param queryNodeId 栏目
     * @param queryNodeType 类型
     * @param queryInfoPermType
     * @param queryStatus 状态
     * @param returnUrl 返回url
     * @param targetNodeId 目标栏目
     * @param orderId
     * @param pageable 分页对象
     * @param request 请求对象
     * @param modelMap
     * @return
     */
    //    @RequiresPermissions("core:livenode:list")
    @RequestMapping("livelist.do")
    public String livelist(Integer queryNodeId, Integer queryNodeType, Integer queryInfoPermType, String queryStatus,
                           String returnUrl, Integer targetNodeId, Integer orderId,
                           @PageableDefault(sort = {"publishDate", "id"}, direction = Sort.Direction.DESC) Pageable pageable,
                           HttpServletRequest request, org.springframework.ui.Model modelMap) {
        String url = "core/node_live/liveinfo_list";
//        if(returnUrl!=null){
//            url="core/publish_center/"+returnUrl;
//        }
        queryNodeType = queryNodeType == null ? 0 : queryNodeType;
        Integer siteId = Context.getCurrentSiteId();
        User user = Context.getCurrentUser();
        Integer nodeId = queryNodeId;
        Integer mainNodeId = null;
        String treeNumber = null;
        Node queryNode = null;
        if (queryNodeId != null) {
            queryNode = nodeQuery.get(queryNodeId);
        }
        if (queryNode != null) {
            if (queryNodeType == INCLUDE_MULTI) {
                nodeId = queryNodeId;
            } else if (queryNodeType == MAIN_NODE) {
                mainNodeId = queryNodeId;
            } else {
                treeNumber = queryNode.getTreeNumber();
            }
        }
        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);
        int infoPermType = user.getInfoPermType(siteId);
        if (queryInfoPermType != null && queryInfoPermType > infoPermType) {
            infoPermType = queryInfoPermType;
        }
        boolean allInfoPerm = user.getAllInfoPerm(siteId);
        infoPermType = 1; //所有信息权限
        List<Attribute> attributeList = attributeService.findList(siteId);
        Page<Info> pagedList = infoQuery.findAll(null, siteId, mainNodeId, nodeId, null, null, true,
                infoPermType, queryStatus, params, pageable, null);
        modelMap.addAttribute("pagedList", pagedList);
        modelMap.addAttribute("attributeList", attributeList);
        modelMap.addAttribute("queryNodeId", queryNodeId);
        modelMap.addAttribute("queryNodeType", queryNodeType);
        modelMap.addAttribute("queryInfoPermType", queryInfoPermType);
        modelMap.addAttribute("queryStatus", queryStatus);
        modelMap.addAttribute("node", queryNode);
        modelMap.addAttribute("returnUrl", returnUrl);
        modelMap.addAttribute("targetNodeId", targetNodeId);
        modelMap.addAttribute("orderId", orderId);
        return url;
    }


    /**
     * 精选直播
     * @param queryNodeId 栏目
     * @param queryNodeType 类型
     * @param queryInfoPermType 权限范围
     * @param queryStatus 状态
     * @param returnUrl 返回url
     * @param targetNodeId 目标栏目
     * @param orderId
     * @param pageable 分页对象
     * @param request
     * @param modelMap
     * @return 结果页面
     */
//    @RequiresPermissions("core:selectlive:list")
    @RequestMapping("selectlivelist.do")
    public String selectlivelist(Integer queryNodeId, Integer queryNodeType, Integer queryInfoPermType, String queryStatus,
                                 String returnUrl, Integer targetNodeId, Integer orderId,
                                 @PageableDefault(sort = {"publishDate", "id"}, direction = Sort.Direction.DESC) Pageable pageable,
                                 HttpServletRequest request, org.springframework.ui.Model modelMap) {
        String url = "core/node_live/live_list";
//        if(returnUrl!=null){
//            url="core/publish_center/"+returnUrl;
//        }
        queryNodeType = queryNodeType == null ? 0 : queryNodeType;
        Integer siteId = Context.getCurrentSiteId();
        User user = Context.getCurrentUser();
        Integer nodeId = queryNodeId;
        Integer mainNodeId = null;
        String treeNumber = null;
        Node queryNode = null;
        if (queryNodeId != null) {
            queryNode = nodeQuery.get(queryNodeId);
        }
        if (queryNode != null) {
            if (queryNodeType == INCLUDE_MULTI) {
                nodeId = queryNodeId;
            } else if (queryNodeType == MAIN_NODE) {
                mainNodeId = queryNodeId;
            } else {
                treeNumber = queryNode.getTreeNumber();
            }
        }
        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);
        int infoPermType = user.getInfoPermType(siteId);
        if (queryInfoPermType != null && queryInfoPermType > infoPermType) {
            infoPermType = queryInfoPermType;
        }
        boolean allInfoPerm = user.getAllInfoPerm(siteId);

        Sort defSort = new Sort(Sort.Direction.DESC, "priority");
        Limitable limitable = new LimitRequest(null, null, defSort);
//        Integer[] liveStatus = new Integer[]{1};
        List<Info> list = infoQuery.findList(null, new Integer[]{nodeId}, null,
                null, null, new Integer[]{siteId}, null, null, null,
                null, null, null, null, null,
                null, null, null, null, null,
                null, null, null, null, null, null,
                null, null, null, null, null, null, limitable,null);
        if (list != null && list.size() > 0) {
            for (Info bean : list) {
                String desc = bean.getRefLive().getIntroduction();
                if (StringUtils.isNotBlank(desc)) {
                    desc = desc.replaceAll("\\r\\n", "<br>");
                }
                if (bean.getPriority() != null && bean.getPriority().intValue() == 0) {
                    modelMap.addAttribute("live1", bean);
                    modelMap.addAttribute("desc1", desc);
                } else if (bean.getPriority() != null && bean.getPriority().intValue() == 1) {
                    modelMap.addAttribute("live2", bean);
                    modelMap.addAttribute("desc2", desc);
                } else if (bean.getPriority() != null && bean.getPriority().intValue() == 2) {
                    modelMap.addAttribute("live3", bean);
                    modelMap.addAttribute("desc3", desc);
                } else if (bean.getPriority() != null && bean.getPriority().intValue() == 3) {
                    modelMap.addAttribute("live4", bean);
                    modelMap.addAttribute("desc4", desc);
                }
            }
        }
        List<Attribute> attributeList = attributeService.findList(siteId);
        modelMap.addAttribute("attributeList", attributeList);
        modelMap.addAttribute("queryNodeId", queryNodeId);
        modelMap.addAttribute("queryNodeType", queryNodeType);
        modelMap.addAttribute("queryInfoPermType", queryInfoPermType);
        modelMap.addAttribute("queryStatus", queryStatus);
        modelMap.addAttribute("node", queryNode);
        modelMap.addAttribute("returnUrl", returnUrl);
        modelMap.addAttribute("targetNodeId", targetNodeId);
        modelMap.addAttribute("orderId", orderId);
        return url;
    }


    /**
     * 查询直播（直播、精选直播栏目添加直播）
     * @param pageable 分页
     * @param queryNodeId 栏目
     * @param liveStatus 直播状态
     * @param order 顺序
     * @param infoId
     * @param request
     * @param modelMap
     * @return 结果页面
     */
    @RequiresPermissions("core:chooselive:chooselivelist")
    @RequestMapping("chooselivelist.do")
    public String chooselivelist(
            @PageableDefault(sort = "id", direction = Sort.Direction.DESC) Pageable pageable,
            Integer queryNodeId, Integer liveStatus, Integer order, Integer infoId,
            HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Integer siteId = Context.getCurrentSiteId();
        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);
        if (liveStatus != null) {
            params.put("EQ_status", new String[]{liveStatus.toString()});
        }
        Page<LiveBroadcast> pagedList = liveBroadcastService.findAll(siteId, params, pageable);
        modelMap.addAttribute("pagedList", pagedList);
        modelMap.addAttribute("queryNodeId", queryNodeId);
        modelMap.addAttribute("liveStatus", liveStatus);
        modelMap.addAttribute("order", order);
        modelMap.addAttribute("infoId", infoId);
        return "core/node_live/livebroadcast_list";
    }


    //    @RequiresPermissions("core:live:ref")
    @RequestMapping("refLive.do")
    public String refLive(
            Integer[] ids, Integer queryNodeId, Integer queryNodeType, Integer queryInfoPermType,
            String queryStatus, HttpServletRequest request, RedirectAttributes ra) {
        Integer siteId = Context.getCurrentSiteId();

//        Page<LiveBroadcast> pagedList = liveBroadcastService.findAll(siteId, params, pageable);
//        modelMap.addAttribute("pagedList", pagedList);
        return "core/node_live/liveinfo_list";
    }

    /**
     * 直播、精选添加直播引用
     * @param bean
     * @param detail
     * @param nodeIds
     * @param specialIds
     * @param viewGroupIds
     * @param viewOrgIds
     * @param attrIds
     * @param nodeId
     * @param tagKeywords
     * @param order 顺序
     * @param draft
     * @param imagesName
     * @param imagesText
     * @param imagesImage
     * @param filesName
     * @param filesFile
     * @param filesLength
     * @param redirect
     * @param queryNodeId
     * @param queryNodeType
     * @param queryInfoPermType
     * @param queryStatus
     * @param refLiveId 直播id
     * @param infoId
     * @param voteIds
     * @param request
     * @param ra
     * @return 结果页面
     */
    //    @RequiresPermissions("core:live:info:save")
    @RequestMapping("liveinfosave.do")
    public String liveinfosave(Info bean,InfoDetail detail, Integer[] nodeIds, Integer[] specialIds, Integer[] viewGroupIds,
                               Integer[] viewOrgIds, Integer[] attrIds, Integer nodeId, String tagKeywords, Integer order,
                               @RequestParam(defaultValue = "false") boolean draft, String[] imagesName, String[] imagesText,
                               String[] imagesImage, String[] filesName, String[] filesFile, Long[] filesLength, String redirect,
                               Integer queryNodeId, Integer queryNodeType, Integer queryInfoPermType, String queryStatus,
                               Integer refLiveId, Integer infoId, Integer[] voteIds,
                               HttpServletRequest request, RedirectAttributes ra) {
        String url = "redirect:livelist.do";
        Integer siteId = Context.getCurrentSiteId();
        Integer userId = Context.getCurrentUserId();
        User user = Context.getCurrentUser();
        if(specialIds!=null && specialIds.length==1){
            if(specialIds[0]==null){
                specialIds=null;
            }
        }
        if(voteIds!=null && voteIds.length==1){
            if(voteIds[0]==null){
                voteIds=null;
            }
        }
        Map<String, String> customs = Servlets.getParamMap(request, "customs_");
        Map<String, String> clobs = Servlets.getParamMap(request, "clobs_");
        if (StringUtils.isBlank(detail.getMetaDescription())) {
            String title = detail.getTitle();
            detail.setMetaDescription(Info.getDescription(clobs, title));
        }
        String[] tagNames = splitTagKeywords(tagKeywords);
        Map<String, String> attrImages = Servlets.getParamMap(request, "attrImages_");
        for (Map.Entry<String, String> entry : attrImages.entrySet()) {
            entry.setValue(StringUtils.trimToNull(entry.getValue()));
        }
        List<InfoImage> images = new ArrayList<InfoImage>();
        if (imagesName != null) {
            InfoImage infoImage;
            for (int i = 0, len = imagesName.length; i < len; i++) {
                if (StringUtils.isNotBlank(imagesName[i]) || StringUtils.isNotBlank(imagesText[i])
                        || StringUtils.isNotBlank(imagesImage[i])) {
                    infoImage = new InfoImage(imagesName[i], imagesText[i], imagesImage[i]);
                    images.add(infoImage);
                }
            }
        }
        List<InfoFile> files = new ArrayList<InfoFile>();
        if (filesName != null) {
            InfoFile infoFile;
            for (int i = 0, len = filesFile.length; i < len; i++) {
                if (StringUtils.isNotBlank(filesName[i]) && StringUtils.isNotBlank(filesFile[i])) {
                    infoFile = new InfoFile(filesName[i], filesFile[i], filesLength[i]);
                    files.add(infoFile);
                }
            }
        }
        //引用直播
        if (refLiveId != null) {
            LiveBroadcast live = liveBroadcastService.get(refLiveId);
            bean.setNewsType(5);   //直播新闻
            bean.setRefLive(live);
            detail.setTitle(live.getTitle());
            if (order != null) {
                bean.setPriority(order);
                url = "redirect:selectlivelist.do";
            }
        }
        String status = draft ? Info.DRAFT : null;
        bean.setStatus("A"); //正常，已发布
        //精选直播栏目
        if(order!=null && nodeId!=null){
            Limitable limitable =new LimitRequest(0,99999, Sort.Direction.DESC,"publishDate");
            List<Info> list = infoQuery.findList(null,new Integer[]{nodeId}, null,
                    null, null,new Integer[]{siteId} , null,null, null,
                    null, null, null, null,new Integer[]{order},
                    null, null, null, null,null,
                    null, null, null,null,null, null,
                    null, null, null, null, null, null, limitable,null);
            if(list!=null && list.size()>0 && infoId==null){ //添加 当前位置已有数据
                ra.addFlashAttribute(MESSAGE,DATA_EXIST);
            }else if(infoId!=null){   //变更
                if(list!=null && list.size()>0){  //变更先清理数据
                    for(Info info:list){
                        if(info!=null && info.getRefLive()!=null && order.intValue()==info.getPriority().intValue()){
                            infoService.delete(info.getId());
                        }
                    }
                }
                Info result = infoService.save(bean, detail, nodeIds, specialIds, viewGroupIds, viewOrgIds, voteIds, customs, clobs, images, files,
                            attrIds, attrImages, tagNames, nodeId, userId, status, siteId);
                ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
                String ip = Servlets.getRemoteAddr(request);
                logService.operation("opr.info.liveinfosave", bean.getTitle(), null, bean.getId(), ip, userId, siteId);
                logger.info("save Info, title={}.", bean.getTitle());
            }else if(list==null || list.size()==0){ //添加
                Info result = infoService.save(bean, detail, nodeIds, specialIds, viewGroupIds, viewOrgIds, voteIds, customs, clobs, images, files,
                        attrIds, attrImages, tagNames, nodeId, userId, status, siteId);
                ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
                String ip = Servlets.getRemoteAddr(request);
                logService.operation("opr.info.liveinfosave", bean.getTitle(), null, bean.getId(), ip, userId, siteId);
                logger.info("save Info, title={}.", bean.getTitle());
            }
        }else{
            //非精选直播 order不传值
            if (infoId == null) {
                Info result = infoService.save(bean, detail, nodeIds, specialIds, viewGroupIds, viewOrgIds, voteIds, customs, clobs, images, files,
                        attrIds, attrImages, tagNames, nodeId, userId, status, siteId);
            }
            ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
            String ip = Servlets.getRemoteAddr(request);
            logService.operation("opr.info.liveinfosave", bean.getTitle(), null, bean.getId(), ip, userId, siteId);
            logger.info("save Info, title={}.", bean.getTitle());
        }

        ra.addAttribute("queryNodeId", nodeId);
        ra.addAttribute("queryNodeType", queryNodeType);
        ra.addAttribute("queryInfoPermType", queryInfoPermType);
        ra.addAttribute("queryStatus", queryStatus);
        ra.addAttribute("id", bean.getId());
        ra.addAttribute("returnUrl", "core/publish_center/focus_list");
        return url;
    }


    /**
     * 清除直播引用
     * @param ids
     * @param queryNodeId 栏目
     * @param queryNodeType
     * @param queryInfoPermType
     * @param returnUrl 返回url
     * @param queryStatus 状态
     * @param request
     * @param ra
     * @return 结果页面
     */
    @RequiresPermissions(value = {
            "core:liveref:delete",
            "core:liveref:liverefdelete",
    }, logical = Logical.OR)
    @RequestMapping("liverefdelete.do")
    public String liverefdelete(Integer[] ids, Integer queryNodeId, Integer queryNodeType, Integer queryInfoPermType,
                                String returnUrl,
                                String queryStatus, HttpServletRequest request, RedirectAttributes ra) {
        if (returnUrl == null) {
            returnUrl = "redirect:livelist.do";
        } else {
            returnUrl = "redirect:" + returnUrl + ".do";
        }
        Site site = Context.getCurrentSite();
        User user = Context.getCurrentUser();
        validateIds(ids, site.getId());
        for (Integer id : ids) {
            Info bean = infoQuery.get(id);
            if(bean!=null){
                if (!bean.isDataPerm(user) || !bean.isAuditPerm(user)) {
                    throw new CmsException("accessDenied");
                }
            }
        }
        List<Info> beans = infoService.delete(ids);
//        infoService.batchupdateHtmlThread(Arrays.asList(ids),true,"firePostDelete");
        String ip = Servlets.getRemoteAddr(request);
        for (Info bean : beans) {
            logService
                    .operation("opr.info.delete", bean.getTitle(), null, bean.getId(), ip, user.getId(), site.getId());
            logger.info("delete Info, name={}.", bean.getTitle());
        }
        ra.addAttribute("queryNodeId", queryNodeId);
        ra.addAttribute("queryNodeType", queryNodeType);
        ra.addAttribute("queryInfoPermType", queryInfoPermType);
        ra.addAttribute("queryStatus", queryStatus);
        ra.addFlashAttribute(MESSAGE, DELETE_SUCCESS);
        return returnUrl;
    }


    //    @RequiresPermissions("core:flash_new:save")
    @RequestMapping("flashNewSave.do")
    public String flashNewSave(Integer[] ids, Integer infoId, Integer orderId, Integer targetNodeId,
                               Integer queryNodeId, Integer queryNodeType, String returnUrl,
                               Integer queryInfoPermType, String queryStatus, HttpServletRequest request, RedirectAttributes ra) {
        Site site = Context.getCurrentSite();
        User user = Context.getCurrentUser();
        ids = new Integer[1];
        ids[0] = infoId;
//        validateIds(ids, site.getId());

//        infoService.updateInfoRef(ids,targetNodeId,orderId);

        Integer[] sourceIds = getNodeIdsByFlag(Constants.MODEL_FLAG_24HOURSNEWS, site, user);
        Integer[] targetIds = getNodeIdsByFlag(Constants.MODEL_FLAG_NEWSFLASH, site, user);

        Map<String, Object> timerMap = new HashMap<>();
        timerMap.put("sourceNodeId", sourceIds[0]);
        timerMap.put("targetNodeId", targetIds[0]);
        timerMap.put("flashBigNewService", flashBigNewService);
        QuartzUtils quartz = new QuartzUtils();
        quartz.start();
        quartz.addJob("快讯定时更新", "新闻", FlashNewJob.class, "0/20 * * * * ?", timerMap);
//        String ip = Servlets.getRemoteAddr(request);
//        for (Integer id : ids) {
//            Info bean=infoQuery.get(id);
//            logService.operation("core:info:focusRefInfo", bean.getTitle(), null, bean.getId(), ip, user.getId(), site.getId());
//            logger.info("{} focusRefInfo Info, title={}.", bean.getTitle(),user.getId());
//
//        }
//        ra.addAttribute("queryNodeId", queryNodeId);
//        ra.addAttribute("orderId", orderId);
//        ra.addAttribute("queryNodeType", queryNodeType);
//        ra.addAttribute("queryInfoPermType", queryInfoPermType);
//        ra.addAttribute("queryStatus", queryStatus);
//        ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
//        ra.addAttribute("returnUrl",returnUrl );
//        ra.addAttribute("showInfoId", infoId);
        return "core/current_hour/scrollinfo";
    }

    private Integer[] getNodeIdsByFlag(String modelFlag, Site site, User user) {
        Integer[] nodeIds = null;
        Map<String, String[]> paramMap = new HashMap<String, String[]>();
        paramMap.put("EQ_flag", new String[]{modelFlag});
        List<Model> models = modelService.findList(site.getId(), null, paramMap, null);

        paramMap = new HashMap<String, String[]>();
        String[] idsStr;
        if (models != null && models.size() > 0) {
            idsStr = new String[models.size()];
            for (int i = 0; i < models.size(); i++) {
                idsStr[i] = models.get(i).getId().toString();
            }
            paramMap.put("EQ_nodeModel.id", idsStr);
        }
        Sort paramSort = new Sort(Sort.Direction.ASC, "treeNumber", "id");
        List<Node> currentNodeList = nodeQuery.findList(site.getId(), null,
                null, null, true,
                paramMap, paramSort);
//        currentNodeList= user.getInfoPermList(site.getId(), currentNodeList);
        if (currentNodeList != null) {
            nodeIds = new Integer[currentNodeList.size()];
            for (int i = 0; i < currentNodeList.size(); i++) {
                nodeIds[i] = (currentNodeList.get(i).getId());
            }
        }
        return nodeIds;
    }

    @RequiresPermissions(value = {
            "core:current_hour:chooseinfolist"
    }, logical = Logical.OR)
    @RequestMapping("chooseinfolist.do")
    public String chooseinfolist(Integer queryNodeId, Integer queryNodeType, Integer queryInfoPermType, String queryStatus,
                                 String returnUrl, Integer connInfoid, String title, String tab,
                                 @PageableDefault(sort = {"publishDate", "id"}, direction = Sort.Direction.DESC) Pageable pageable,
                                 HttpServletRequest request, org.springframework.ui.Model modelMap) {
        queryNodeType = queryNodeType == null ? 0 : queryNodeType;
        Integer siteId = Context.getCurrentSiteId();
        User user = Context.getCurrentUser();
        Integer nodeId = queryNodeId;
        Integer mainNodeId = null;
        String treeNumber = null;
        Node queryNode = null;
        if (queryNodeId != null) {
            queryNode = nodeQuery.get(queryNodeId);
        }
        if (queryNode != null) {
            if (queryNodeType == INCLUDE_MULTI) {
                nodeId = queryNodeId;
            } else if (queryNodeType == MAIN_NODE) {
                mainNodeId = queryNodeId;
            } else {
                treeNumber = queryNode.getTreeNumber();
            }
        }
        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);
        int infoPermType = user.getInfoPermType(siteId);
        if (queryInfoPermType != null && queryInfoPermType > infoPermType) {
            infoPermType = queryInfoPermType;
        }
        boolean allInfoPerm = user.getAllInfoPerm(siteId);
        Page<Info> pagedList = infoQuery.findAll(null, siteId, mainNodeId, nodeId, treeNumber, null, allInfoPerm,
                infoPermType, queryStatus, params, pageable, null);

        List<Attribute> attributeList = attributeService.findList(siteId);
        modelMap.addAttribute("pagedList", pagedList);
        modelMap.addAttribute("attributeList", attributeList);
        modelMap.addAttribute("queryNodeId", queryNodeId);
        modelMap.addAttribute("queryNodeType", queryNodeType);
        modelMap.addAttribute("queryInfoPermType", queryInfoPermType);
        modelMap.addAttribute("queryStatus", queryStatus);
        modelMap.addAttribute("node", queryNode);
        modelMap.addAttribute("returnUrl", returnUrl);
        modelMap.addAttribute("connInfoid", connInfoid);
        modelMap.addAttribute("title", title);
        modelMap.addAttribute("tab", tab);
        return returnUrl;
    }

    //    @RequiresPermissions("core:flash_new:list")
    @RequestMapping("list.do")
    public String list(Integer[] ids, Integer connInfoid, String title, String tab,
                       Integer queryNodeId, Integer queryNodeType,
                       Integer queryInfoPermType, String queryStatus, HttpServletRequest request, RedirectAttributes ra,
                       org.springframework.ui.Model modelMap) {
        Info connInfo = null;
        if (connInfoid != null) {
            connInfo = infoQuery.get(connInfoid);
        }
        modelMap.addAttribute("queryNodeId", queryNodeId);
        modelMap.addAttribute("queryNodeType", queryNodeType);
        modelMap.addAttribute("queryInfoPermType", queryInfoPermType);
        modelMap.addAttribute("queryStatus", queryStatus);
        modelMap.addAttribute("connInfo", connInfo);
        modelMap.addAttribute("title", title);
        modelMap.addAttribute("tab", tab);

        return "core/flash_big_news/scrollinfo";
    }

    //    @RequiresPermissions("core:info:save")
    @RequestMapping("infosave.do")
    public String infosave(Info bean, InfoDetail detail, Integer[] nodeIds, Integer[] specialIds, Integer[] viewGroupIds, Integer[] voteIds,
                           Integer[] viewOrgIds, Integer[] attrIds, Integer nodeId, String tagKeywords, String tab, Integer connInfoid,
                           @RequestParam(defaultValue = "false") boolean draft, String[] imagesName, String[] imagesText,
                           String[] imagesImage, String[] filesName, String[] filesFile, Long[] filesLength, String redirect,
                           Integer queryNodeId, Integer queryNodeType, Integer queryInfoPermType, String queryStatus,
                           HttpServletRequest request, RedirectAttributes ra) {

        Site site = Context.getCurrentSite();
        User user = Context.getCurrentUser();
        Integer siteId = site.getId();
        Integer userId = user.getId();

        //重磅新闻参数
        Integer[] ids = getNodeIdsByFlag(Constants.MODEL_FLAG_BIGNEWS, site, user);
        nodeId = ids[0];
        if (connInfoid != null) {
            Info connInfo = infoQuery.get(connInfoid);
            bean.setRefInfo(connInfo);
        }

        Map<String, String> customs = Servlets.getParamMap(request, "customs_");
        Map<String, String> clobs = Servlets.getParamMap(request, "clobs_");
        if (StringUtils.isBlank(detail.getMetaDescription())) {
            String title = detail.getTitle();
            detail.setMetaDescription(Info.getDescription(clobs, title));
        }
        String[] tagNames = splitTagKeywords(tagKeywords);
        Map<String, String> attrImages = Servlets.getParamMap(request, "attrImages_");
        for (Map.Entry<String, String> entry : attrImages.entrySet()) {
            entry.setValue(StringUtils.trimToNull(entry.getValue()));
        }
        List<InfoImage> images = new ArrayList<InfoImage>();
        if (imagesName != null) {
            InfoImage infoImage;
            for (int i = 0, len = imagesName.length; i < len; i++) {
                if (StringUtils.isNotBlank(imagesName[i]) || StringUtils.isNotBlank(imagesText[i])
                        || StringUtils.isNotBlank(imagesImage[i])) {
                    infoImage = new InfoImage(imagesName[i], imagesText[i], imagesImage[i]);
                    images.add(infoImage);
                }
            }
        }
        List<InfoFile> files = new ArrayList<InfoFile>();
        if (filesName != null) {
            InfoFile infoFile;
            for (int i = 0, len = filesFile.length; i < len; i++) {
                if (StringUtils.isNotBlank(filesName[i]) && StringUtils.isNotBlank(filesFile[i])) {
                    infoFile = new InfoFile(filesName[i], filesFile[i], filesLength[i]);
                    files.add(infoFile);
                }
            }
        }
        if(specialIds!=null && specialIds.length==1){
            if(specialIds[0]==null){
                specialIds=null;
            }
        }
        if(voteIds!=null && voteIds.length==1){
            if(voteIds[0]==null){
                voteIds=null;
            }
        }
        String status = draft ? Info.DRAFT : null;
        bean.setStatus("A"); //正常，已发布
        Info result = infoService.save(bean, detail, nodeIds, specialIds, viewGroupIds, viewOrgIds, voteIds, customs, clobs, images, files,
                attrIds, attrImages, tagNames, nodeId, userId, status, siteId);

//        infoService.updateHtmlThread(result.getId(),false,"firePostSave");
        String ip = Servlets.getRemoteAddr(request);
        logService.operation("opr.info.add", bean.getTitle(), null, bean.getId(), ip, userId, siteId);
        logger.info("save Info, title={}.", bean.getTitle());
        ra.addAttribute("queryNodeId", queryNodeId);
        ra.addAttribute("queryNodeType", queryNodeType);
        ra.addAttribute("queryInfoPermType", queryInfoPermType);
        ra.addAttribute("queryStatus", queryStatus);
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        ra.addAttribute("tab", tab);
//        if (Constants.REDIRECT_LIST.equals(redirect)) {
//            ra.addAttribute("returnUrl","core/current_hour/currentnews_list");
//            return "redirect:list.do";
//        } else if (Constants.REDIRECT_CREATE.equals(redirect)) {
//            return "redirect:infocreate.do";
//        } else {
//            ra.addAttribute("id", bean.getId());
//            return "redirect:infoedit.do";
//        }
        return "redirect:list.do";
    }

    /**
     * 生成直播数据
     * @param queryNodeId 栏目
     * @param returnUrl 返回url
     * @param ra
     * @param request
     * @param modelMap
     * @return 结果页面
     */
    @RequestMapping("generationLive.do")
//    @RequiresRoles("super")
    @RequiresPermissions(value = {
            "core:sinatv:generationLive",
            "core:sinatv:generationLive01"
    }, logical = Logical.OR)
    public String generationLive(Integer queryNodeId, String returnUrl, RedirectAttributes ra,
                                 HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Node queryNode = null;
        if (queryNodeId != null) {
            queryNode = nodeQuery.get(queryNodeId);
            Site site = Context.getCurrentSite();
            User user = Context.getCurrentUser();
//            htmlGenerator.makeInfo(site.getId(), queryNodeId, queryNode.getName(), true, user.getId());
//            htmlService.makeNode(queryNodeId);
            htmlGenerator.makeNode(site.getId(), queryNodeId, queryNode.getName(), true, user.getId(), null);
            String ip = Servlets.getRemoteAddr(request);
            logService.operation("opr.generationLive", queryNode.getName(), null, queryNodeId, ip, user.getId(), site.getId());
            logger.info("generationLive json Info, node={}.", queryNode.getName());
        }
        ra.addAttribute("queryNodeId", queryNodeId);
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        return "redirect:" + returnUrl + ".do";
    }

    @ModelAttribute
    public void preloadNodeBean(@RequestParam(required = false) Integer oid, org.springframework.ui.Model modelMap) {
        if (oid != null) {
            Node bean = nodeQuery.get(oid);
            if (bean != null) {
                modelMap.addAttribute("bean", bean);
                NodeDetail detail = bean.getDetail();
                if (detail == null) {
                    detail = new NodeDetail();
                    detail.setId(oid);
                    detail.setNode(bean);
                }
                modelMap.addAttribute("detail", detail);
            }
        }
    }

    @ModelAttribute
    public void preloadInfoBean(@RequestParam(required = false) Integer oid, org.springframework.ui.Model modelMap) {
        if (oid != null) {
            Info bean = infoQuery.get(oid);
            if (bean != null) {
                modelMap.addAttribute("bean", bean);
                InfoDetail detail = bean.getDetail();
                if (detail == null) {
                    detail = new InfoDetail();
                    detail.setId(oid);
                    detail.setInfo(bean);
                }
                modelMap.addAttribute("detail", detail);
            }
        }
    }

    private void validateIds(Integer[] ids, Integer siteId) {
        for (Integer id : ids) {
            Backends.validateDataInSite(nodeQuery.get(id), siteId);
        }
    }

    private Integer[] getInfoPermIds(Integer siteId, Integer parentId) {
        Collection<Role> roles = null;
        if (parentId != null) {
            Node node = nodeQuery.get(parentId);
            if (node != null) {
                roles = node.getInfoPerms();
            }
        }
        if (roles == null) {
            roles = roleService.findList(siteId);
        }
        int len = roles.size();
        Integer[] ids = new Integer[len];
        int i = 0;
        for (Role role : roles) {
            ids[i++] = role.getId();
        }
        return ids;
    }

    private Integer[] getNodePermIds(Integer siteId, Integer parentId) {
        Collection<Role> roles = null;
        if (parentId != null) {
            Node node = nodeQuery.get(parentId);
            if (node != null) {
                roles = node.getNodePerms();
            }
        }
        if (roles == null) {
            roles = roleService.findList(siteId);
        }
        int len = roles.size();
        Integer[] ids = new Integer[len];
        int i = 0;
        for (Role role : roles) {
            ids[i++] = role.getId();
        }
        return ids;
    }

    private Integer[] getViewGroupIds(Integer siteId, Integer parentId) {
        Collection<MemberGroup> groups = null;
        if (parentId != null) {
            Node node = nodeQuery.get(parentId);
            if (node != null) {
                groups = node.getViewGroups();
            }
        }
        if (groups == null) {
            groups = memberGroupService.findList();
        }
        int len = groups.size();
        Integer[] ids = new Integer[len];
        int i = 0;
        for (MemberGroup group : groups) {
            ids[i++] = group.getId();
        }
        return ids;
    }

    private Integer[] getContriGroupIds(Integer siteId, Integer parentId) {
        Collection<MemberGroup> groups = null;
        if (parentId != null) {
            Node node = nodeQuery.get(parentId);
            if (node != null) {
                groups = node.getContriGroups();
            }
        }
        if (groups == null) {
            groups = memberGroupService.findList();
        }
        int len = groups.size();
        Integer[] ids = new Integer[len];
        int i = 0;
        for (MemberGroup group : groups) {
            ids[i++] = group.getId();
        }
        return ids;
    }

    private Integer[] getCommentGroupIds(Integer siteId, Integer parentId) {
        Collection<MemberGroup> groups = null;
        if (parentId != null) {
            Node node = nodeQuery.get(parentId);
            if (node != null) {
                groups = node.getCommentGroups();
            }
        }
        if (groups == null) {
            groups = memberGroupService.findList();
        }
        int len = groups.size();
        Integer[] ids = new Integer[len];
        int i = 0;
        for (MemberGroup group : groups) {
            ids[i++] = group.getId();
        }
        return ids;
    }

    private String[] splitTagKeywords(String tagKeywords) {
        String split = Constants.TAG_KEYWORDS_SPLIT;
        if (StringUtils.isNotBlank(split)) {
            for (int i = 0, len = split.length(); i < len; i++) {
                tagKeywords = StringUtils.replace(tagKeywords, String.valueOf(split.charAt(i)), ",");
            }
        }
        return StringUtils.split(tagKeywords, ',');
    }

    @Autowired
    private OperationLogService logService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private MemberGroupService memberGroupService;
    @Autowired
    private WorkflowService workflowService;
    @Autowired
    private ModelService modelService;
    @Autowired
    private NodeService service;
    @Autowired
    private NodeQueryService nodeQuery;
    @Autowired
    private AttributeService attributeService;
    @Autowired
    private InfoQueryService infoQuery;
    @Autowired
    private InfoService infoService;
    @Autowired
    private HtmlService htmlService;
    @Autowired
    private InfoNodeService infoNodeService;
    @Autowired
    private FlashBigNewService flashBigNewService;
    @Autowired
    private LiveBroadcastService liveBroadcastService;
    @Autowired
    private HtmlGenerator htmlGenerator;


}
